#!/usr/bin/python3


from optparse import OptionParser
import sys
import os

sys.path.append("/usr/lib/linx-sec-center")
import ct_core

def create_parser():
    USAGE_MES="%prog [-a|--append]\
            \n  Default: when you input no argument, you could input mac\
            \n          rules in stdin, and when you finished, Ctrl+D\
            \n          will be back and write the new label to system if the\
            \n          The inputs correct\
            \n Example:\
            \n secadmin~$ %prog \
            \n f1 > r-\
            \n f2 { -w\
            \n EOF          "
    parse = OptionParser(usage=USAGE_MES,version="%prog 1.0")
    parse.add_option("-a","--append",action="store_true", dest="append", help="add a mac rules to system")
    parse.add_option("-c","--clear",action="store_true", dest="clear", help="clear mac rules of the system")
    return parse

def set_rules_label(flg=''):
    if flg != '':
        ct_core.get_mac_rules_label()
    print("Please input the new mac rules:")
    line = sys.stdin.readlines()
    for l in line:
        ls = l.split()
        if len(ls) != 3:
            print("Sorry, you input mac rules %s is error!" %ls)
            return 
        fld,rel,per = ls 
        if not ct_core.set_mac_rules_label(fld, rel, per):
            return 
    ct_core.write_mac_rules_file()

def clear_rules_label():
    ct_core.d_rules_label.clear()
    ct_core.write_mac_rules_file()
    print("Clear mac rules done!")

def main():
    parser = create_parser()
    args,flg = parser.parse_args()

    if args.append:
        set_rules_label('a')
    elif args.clear:
        clear_rules_label()
    elif not flg:
        set_rules_label()
    else:
        parser.error("Argument error, please specify a correct argument")

main()
